﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Net;
using System.IO;
using System.Text;

namespace Killboard.Models
{
    public class EveAPI
    {

        private const string apiRoot = "http://api.eve-online.com";
        private const string killRequest = "/corp/KillLog.xml.aspx";
        
        
        public static string GetKillsXml()
        {

            KillRepository repo = new KillRepository();
            ekbConfig config = repo.GetConfiguration();

            byte[] buf = new byte[8192];

            //TODO: Add this to the database (darn it!)
            string characterID = config.ApiCharacterNumber.ToString();


            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(apiRoot + killRequest);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            string postData = string.Format("userID={0}&apiKey={1}&characterID={2}", config.ApiRetrievalUser, config.ApiRetrievalKey, characterID);
            req.ContentLength = postData.Length;
            StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
            stOut.Write(postData);
            stOut.Close();


            HttpWebResponse response = (HttpWebResponse)
            req.GetResponse();

            // we will read data via the response stream
            Stream resStream = response.GetResponseStream();

            string tempString = null;
            int count = 0;
            StringBuilder sb = new StringBuilder();


            do
            {
                // fill the buffer with data
                count = resStream.Read(buf, 0, buf.Length);

                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to ASCII text
                    tempString = Encoding.ASCII.GetString(buf, 0, count);

                    // continue building the string
                    sb.Append(tempString);
                }
            }
            while (count > 0); // any more data to read?

            return sb.ToString();
        }
    }
}
